package com.u2ds.core.security.shiro.filters;

import com.u2ds.core.entity.SysUsers;
import com.u2ds.core.util.BeanUtil;
import com.u2ds.core.util.PasswordUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by Ethan on 2017/2/15.
 * 将password转换为MD5散列
 */
public class MD5FormAuthenticationFilter extends FormAuthenticationFilter {
    private static Logger logger = LoggerFactory.getLogger(MD5FormAuthenticationFilter.class);

    public static final String AJAX_ACCEPT_CONTENT_TYPE = "text/html;type=ajax";
    public static final String AJAX_SOURCE_PARAM = "ajaxSource";


    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = new PasswordUtil(username, "MD5").encode(getPassword(request));
        return createToken(username, password, request, response);
    }


//    @Override
//    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
//                                     ServletRequest request, ServletResponse response) throws Exception {
//        SysUsers query = new SysUsers();
//        query.setUsername(((UsernamePasswordToken)token).getUsername());
//        SysUsersService sysUsersService = (SysUsersService)WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean("sysUsersService");
//        SysUsers sysUsers = sysUsersService.selectOne(query);
//        Map<String, Object> propertyMap = BeanUtil.getAllProperties(sysUsers, sysUsers.getClass());
//        propertyMap.keySet().forEach(key -> {
//            subject.getSession().setAttribute(key, propertyMap.get(key));
//        });
//        return super.onLoginSuccess(token, subject, request, response);
//    }
//
//    @Override
//    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
//        return super.isAccessAllowed(request, response, mappedValue);
//    }

}
